package com.captcha.demo.controller;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import com.captcha.demo.model.Captcha;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.util.Date;

@RequestMapping("/captcha")
@RestController
public class CaptchaController {
    @Autowired
    private Captcha captcha1;
    @RequestMapping("/getCaptcha")

    public void getCaptcha(HttpServletResponse response, HttpSession session) {

        ShearCaptcha shearcaptcha = CaptchaUtil.createShearCaptcha(captcha1.getWidth(), captcha1.getHeight(), captcha1.getCodeCount(), captcha1.getThickness());
        System.out.println(shearcaptcha.getCode());
        String code = shearcaptcha.getCode();
        session.setAttribute(captcha1.getSession().getCode(),code);
        session.setAttribute(captcha1.getSession().getDate(),new Date());
        try {
            shearcaptcha.write(response.getOutputStream());
            response.setContentType("image/jpeg");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Pragma", "No-cache");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @RequestMapping("/check")
    public Boolean check(String captcha,HttpSession session) {
        if(!StringUtils.hasLength(captcha)) {
            return false;
        }
        Date date = (Date)session.getAttribute(captcha1.getSession().getDate());
        if (date == null || (System.currentTimeMillis() - date.getTime()) > 60000) {
            return false;
        }
        String code = (String) session.getAttribute(captcha1.getSession().getCode());
        return captcha.equalsIgnoreCase(code);
    }
}
